package training.bms.persistence;

import javax.persistence.EntityManagerFactory;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Order;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang.StringUtils;

import training.bms.business.Blog;
import training.bms.business.Blog_;
import training.bms.business.Post;
import training.bms.business.PostSearchOptions;
import training.bms.business.Post_;
import training.framework.presentation.AbstractEntityDao;

public class PostDao extends AbstractEntityDao<Integer, Post, PostSearchOptions> {	
	
	public PostDao(){
		super(EntityManagerFactorySingleton.FACTORY, Post.class);
	}
	
	public PostDao(EntityManagerFactory factory, Class<Post> entityClass) {
		super(EntityManagerFactorySingleton.FACTORY, Post.class);
	}

	@Override
	protected Order toOrder(CriteriaBuilder builder, Root<Post> root) {
		return builder.desc(root.get(Post_.creationDate));
	}

	@Override
	protected Predicate toPredicate(CriteriaBuilder builder, Root<Post> root,
			PostSearchOptions options) {
		
		Predicate blogPredicate;
		Integer blogIdentifier = options.getBlogIdentifier(); 
		if (blogIdentifier == null || blogIdentifier == 0) {
			blogPredicate = builder.conjunction();
		} else {
			blogPredicate = builder.equal(
				// post.blog.identifier
				root.get(Post_.blog).get(Blog_.identifier),
				blogIdentifier
			);
		}

		Predicate titlePredicate;
		String postTitle = options.getTitle();
		if (StringUtils.isBlank(postTitle)) {
			titlePredicate = builder.conjunction();								
		} else {
			titlePredicate = builder.like(
				builder.lower(root.get(Post_.title)), 
				toLikeParameter(postTitle)
			);
		}
			
		Predicate contentPredicate;
		String postDescription = options.getContent();
		if (StringUtils.isBlank(postDescription)) {
			contentPredicate = builder.conjunction();
		} else {
			contentPredicate = builder.like(
				builder.lower(root.get(Post_.content)), 
				toLikeParameter(postDescription)
			);				
		}
		
		Predicate predicate = builder.and(blogPredicate, titlePredicate, contentPredicate);
		return predicate;
	}	
}
